package com.ruyuan.commodity.controller.buyer;

import com.ruyuan.commodity.common.mamager.*;
import com.ruyuan.commodity.enums.RedissonLockEnums;
import com.ruyuan.commodity.model.goods.dos.GoodsSkuDO;
import com.ruyuan.commodity.model.goods.vo.*;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/goods")
public class GoodsBuyerController {


	@Autowired
	private GoodsInfoQueryManager goodsInfoQueryManager;

	@Autowired
	private GoodsManager goodsManager;

	@Autowired
	private GoodsSkuManager goodsSkuManager;

	@Autowired
	private RedissonClient redissonClient;
	/**
	 * 商品详情业务管理器
	 */
	@Autowired
	private GoodsDetailManager goodsDetailManager;

    @ApiOperation(value = "商品详情页，获取商品的详情")
    @GetMapping("/{goodsId}")
    public GoodsDetail getGoodsDetail(@PathVariable("goodsId") Long goodsId) {
    	return goodsDetailManager.getGoodsDetail(goodsId);
	}

    @ApiOperation(value = "商品详情页，获取sku信息")
    @GetMapping("/{goodsId}/skus")
    public List<GoodsSkuVO> getGoodsSkus(@PathVariable("goodsId") Long goodsId) {
		String lockKey = RedissonLockEnums.GOODS_DETAIL_LOCK_PREFIX.getKey() + goodsId;
		RLock lock = redissonClient.getLock(lockKey);
		lock.lock();
		try {
			CacheGoods goods = goodsInfoQueryManager.getFromCache(goodsId);
			return goods.getSkuList();
		} finally {
			lock.unlock();
		}
    }

    @ApiOperation(value = "记录浏览商品次数")
    @GetMapping(value = "/{goodsId}/visit")
    public Integer visitGoods(@PathVariable("goodsId") Long goodsId) {
        return this.goodsManager.visitedGoodsNum(goodsId);
    }

	@ApiOperation(value = "查看商品是否在配送区域 1 有货  0 无货")
	@GetMapping(value = "/{goodsId}/area/{areaId}")
	public Integer checkGoodsArea(@PathVariable("goodsId") Long goodsId, @PathVariable("areaId") Long areaId) {
		return this.goodsInfoQueryManager.checkArea(goodsId, areaId);
	}

	@ApiOperation(value = "根据skuId查询goodsId")
	@GetMapping(value = "/sku/{skuId}/goods-id")
	public Long queryGoods(@PathVariable("skuId") Long skuId) {
		GoodsSkuDO sku = this.goodsSkuManager.getModel(skuId);
		if (sku != null) {
			return sku.getGoodsId();
		}
		return null;
	}


}
